import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * Created by admin on 2017/11/5.
 */
public class ZKApp
{
    private  ZooKeeper zooKeeper=null;
    private String connect="192.168.170.223:2181";
    private final int SESSION_TIMEOUT=3000;
    private Watcher watcher=new Watcher() {
        public void process(WatchedEvent event) {
            System.out.println("process"+event.getType());
        }
    };
    @Before
    public void statUp() throws Exception{
//        public ZooKeeper(String connectString, int sessionTimeout, Watcher watcher)
        zooKeeper=new ZooKeeper(connect,SESSION_TIMEOUT,watcher);

    }

    /**
     * 创建节点，添加数据
     */
    @Test
     public void createNode() throws Exception{
        zooKeeper.create("/node","test".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
     }

    /**
     * 获取节点的数据
     * @throws Exception
     */
    @Test
    public void getNode() throws Exception{
        byte[] data = zooKeeper.getData("/node", null, null);
        System.out.println(new String(data));
    }

    /**
     * 修改节点数据
     * @throws Exception
     */
    @Test
    public void setNode() throws Exception{
        Stat stat = zooKeeper.setData("/node", "hadoop zookeeper".getBytes(), -1);
        System.out.println(stat);
    }

    /**
     * 判断节点的是否存在
     * @throws Exception
     */
    @Test
    public void exsitsNodes() throws Exception{
        Stat exists = zooKeeper.exists("/node", null);
        if(exists==null){
            System.out.println(exists);
        }else {
            System.out.println(exists.getCzxid());
        }
    }

    /**
     * 删除节点
     * @throws Exception
     */
    @Test
    public void deleteNodes() throws Exception{
       zooKeeper.delete("/node",-1);
    }




    @After
    public void stop(){

    }
}
